package com.qiguliuxing.dts.admin.web;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.admin.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.admin.dao.*;
import com.qiguliuxing.dts.admin.dao.dto.ProductPageQuery;
import com.qiguliuxing.dts.admin.dao.dto.ReportFormPageQuery;
import com.qiguliuxing.dts.admin.dao.dto.WeekRange;
import com.qiguliuxing.dts.admin.service.AdminIorderService;
import com.qiguliuxing.dts.admin.service.AdminProductProductionService;
import com.qiguliuxing.dts.admin.util.AuthSupport;
import com.qiguliuxing.dts.core.util.ResponseUtil;
import com.qiguliuxing.dts.db.domain.DailyOrder;
import com.qiguliuxing.dts.db.domain.Iorders;
import com.qiguliuxing.dts.db.domain.ProductProduction;
import com.qiguliuxing.dts.db.service.DailyOrderService;
import com.qiguliuxing.dts.db.service.IoralRawService;
import com.qiguliuxing.dts.db.service.IorderService;
import com.qiguliuxing.dts.db.service.ProductProductionService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/reportForm")
@Validated
public class AdminReportFormController {


    @Autowired
    private AdminProductProductionService adminProductProductionService;
    @Autowired
    private ProductProductionService productProductionService;
    @Autowired
    private AdminIorderService adminIorderService;
    @Autowired
    private DailyOrderService dailyOrderService;
    @Autowired
    private IorderService iorderService;
    private static final Logger logger = LoggerFactory.getLogger(AdminReportFormController.class);

    @RequiresPermissions("admin:reportForm:list")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "报表管理" }, button = "查询")
    @PostMapping("/list")
    public Object list(@RequestBody ReportFormPageQuery reportFormPageQuery/*@RequestParam(defaultValue = "2024-01-01") String startTime, @RequestParam(defaultValue = "2024-12-01")String endTime,@RequestParam(value="batchNumber") String batchNumber, @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "20") Integer limit,
                       @RequestParam(defaultValue = "measure_tine") String sort,
                       @RequestParam(defaultValue = "desc") String order*/) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘131生产发货管理->查询,请求参数:instrumentNumber:{},instrumentName:{},page:{}", reportFormPageQuery.toString());
        DecimalFormat decimalFormat = new DecimalFormat("#0.00");
        PageHelper.startPage(reportFormPageQuery.getPage(), reportFormPageQuery.getLimit());
            String startTime = "";
            String endTime = "";
            List<String> ste = new ArrayList<>();
            ste = reportFormPageQuery.getStartToEnd();
            if (ste != null && !ste.isEmpty()) {
                startTime = ste.get(0).substring(0, 10);
                endTime = ste.get(1).substring(0, 10);
                logger.info(ste.toString());
                logger.info(startTime + endTime);
            }
     /*   List<DailySummeryTemplate> dailySummeryTemplates=new ArrayList<>(); //根据每日分装量汇总*/
        List<MonthSummeryTemplate> monthSummeryTemplates=new ArrayList<>(); //根据产品批号汇总
        List<ProductProduction> productProductions=productProductionService.querySelective(startTime,endTime,"",0,0,"production_date","desc");
              //现在开始按起始时间（每日分装量）统计
           List<Iorders> iorders=iorderService.querySelective(startTime,endTime,null,1,20,"date","desc");
           Double orderCount=0.00;
           Double splitQuantity=0.00;
           Double splitCount=0.00;//
           Double totalOrderCount=0.00;
           Double totalSplitQuantity=0.00;
           Double totalSplitCount=0.00;
           List<String> dates=new ArrayList<>();
           for(Iorders iorder:iorders){

               if(!dates.contains(iorder.getDate())){
                   dates.add(iorder.getDate());
               }


           }
        for(ProductProduction production2:productProductions) {
            MonthSummeryTemplate monthSummeryTemplate = new MonthSummeryTemplate();
            for (Iorders iorders3 : iorders){
                if (iorders3.getBatchNumber()!=null && iorders3.getBatchNumber().equals(production2.getBatchNumber())){
                    splitQuantity = iorders3.getSplitVolume();
                    orderCount = iorders3.getOrderCount1() + iorders3.getOrderCount2() + iorders3.getOrderCount3();
                    splitCount = iorders3.getSplitActivity();
                    totalOrderCount = totalOrderCount + orderCount;
                    totalSplitQuantity = totalSplitQuantity + splitQuantity;
                    totalSplitCount = totalSplitCount + splitCount;
                }
           }
                totalOrderCount=Double.valueOf(decimalFormat.format(totalOrderCount));
               totalSplitQuantity=Double.valueOf(decimalFormat.format(totalSplitQuantity));
               totalSplitCount=Double.valueOf(decimalFormat.format(totalSplitCount));
                monthSummeryTemplate.setBatchNumber(production2.getBatchNumber());
                monthSummeryTemplate.setDate(production2.getProductionDate().toString());
                monthSummeryTemplate.setProductActivity(production2.getProductActivity());
                monthSummeryTemplate.setProductName("碘131化钠口服溶液");
                monthSummeryTemplate.setOrderCount(totalOrderCount);
                monthSummeryTemplate.setUnitMeasurement("Ci(居里)");
                monthSummeryTemplate.setNotes("");
                if(production2.getIsEnd()!=null) {
                    if (production2.getIsEnd() == true) {
                        monthSummeryTemplate.setRemainingActivity(0.00);
                    } else {
                        monthSummeryTemplate.setRemainingActivity(Double.valueOf(decimalFormat.format(production2.getProductActivity() - totalSplitCount)));
                    }
                }else{
                    monthSummeryTemplate.setRemainingActivity(0.00);
                }
                monthSummeryTemplate.setIntervalDecay(Double.valueOf(decimalFormat.format(totalSplitCount-totalOrderCount)));
                monthSummeryTemplates.add(monthSummeryTemplate);
                 totalOrderCount=0.00;
                 totalSplitQuantity=0.00;
                 totalSplitCount=0.00;
        }

           /*for(String s:dates){
               DailySummeryTemplate dailySummeryTemplate=new DailySummeryTemplate();
               List<Iorders> iorders2=new ArrayList<>();
               for(Iorders iorders5:iorders){
                   if(iorders5.getDate()!=null) {
                       if (iorders5.getDate().equals(s)) {
                           iorders2.add(iorders5);
                       }
                   }
               }*/
               /*iorders2=iorders.stream()
                       .filter(person -> s.equals(person.getDate()))
                       .collect(Collectors.toList());*/
               /*for(Iorders iorder4:iorders2){
                   splitQuantity=iorder4.getSplitVolume();
                   orderCount=iorder4.getOrderCount1()+iorder4.getOrderCount2()+iorder4.getOrderCount3();
                   splitCount=iorder4.getSplitActivity();
                   totalOrderCount=totalOrderCount+orderCount;
                   totalSplitQuantity=totalSplitQuantity+splitQuantity;
                   totalSplitCount=totalSplitCount+splitCount;
               }
               totalOrderCount=Double.valueOf(decimalFormat.format(totalOrderCount));
               totalSplitQuantity=Double.valueOf(decimalFormat.format(totalSplitQuantity));
               totalSplitCount=Double.valueOf(decimalFormat.format(totalSplitCount));
               dailySummeryTemplate.setDate(s);
               dailySummeryTemplate.setProductName("碘131化钠口服溶液");
               dailySummeryTemplate.setTotalSplitCount(totalSplitCount);
               dailySummeryTemplate.setTotalOrderCount(totalOrderCount);
               dailySummeryTemplate.setIntervalDecay(Double.valueOf(decimalFormat.format(totalSplitCount-totalOrderCount)));
               for(ProductProduction production:productProductions){
                   if(production.getProductionDate().toString().equals(s)){
                       dailySummeryTemplate.setProductCount(production.getProductActivity());
                   }
               }
               dailySummeryTemplates.add(dailySummeryTemplate);
               totalOrderCount=0.00;
               totalSplitQuantity=0.00;
               totalSplitCount=0.00;
           }*/

               Map<String,Object> data=new HashMap<>();
               data.put("item",monthSummeryTemplates);
              /*data.put("item2",dailySummeryTemplates);*/

              /*long total1 = PageInfo.of(dailySummeryTemplates).getTotal();*/
              long total = PageInfo.of(monthSummeryTemplates).getTotal();
              data.put("total",total);
            /*  data.put("total2",total2);*/


            return ResponseUtil.ok(data);



        }

    @RequiresPermissions("admin:reportForm:byWeek")
    @RequiresPermissionsDesc(menu = { "数据统计", "按周统计" }, button = "查找")
    @PostMapping("/byWeek")
    public Object listByWeek(@RequestBody ReportFormPageQuery reportFormPageQuery) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘131生产发货管理->查询,请求参数:instrumentNumber:{},instrumentName:{},page:{}", reportFormPageQuery.toString());
        DecimalFormat decimalFormat = new DecimalFormat("#0.00");
        PageHelper.startPage(reportFormPageQuery.getPage(), reportFormPageQuery.getLimit());
        String startTime = "";
        String endTime = "";
        List<String> ste = new ArrayList<>();
        ste = reportFormPageQuery.getStartToEnd();
        if (ste != null && !ste.isEmpty()) {
            startTime = ste.get(0).substring(0, 10);
            endTime = ste.get(1).substring(0, 10);
            logger.info(ste.toString());
            logger.info(startTime + endTime);
        }
        if(startTime=="" && endTime==""){
            endTime=LocalDate.now().toString();
            startTime=LocalDate.now().minus(12, ChronoUnit.MONTHS).toString();
        }
        List<WeekRange> weekRanges= IorderSpecial.getWeeksBetween(LocalDate.parse(startTime),LocalDate.parse(endTime));
        Double totalOrderCount=0.00;
        Double totalSplitQuantity=0.00;
        Double totalSplitCount=0.00;
        Integer totalPieces=0;
        Double totalProduction=0.00;
        List<DailySummeryTemplate> dailySummeryTemplates=new ArrayList<>(); //根据每日分装量汇总
        for(WeekRange weekRange:weekRanges){
           DailySummeryTemplate dailySummeryTemplate=new DailySummeryTemplate();
           LocalDate startDay=weekRange.getStart();
          /* String start=startDay+"T07:47:04.079Z";*/
            LocalDate endDay=weekRange.getEnd();
     /*       String end=endDay+"T07:47:04.079Z";*/
            List<Iorders> iorders=iorderService.querySelective(startDay.toString(),endDay.toString(),"",1,30,"desc","");
            for(Iorders iorder:iorders){
                totalOrderCount=totalOrderCount+iorder.getOrderCount1()+iorder.getOrderCount2()+iorder.getOrderCount3();
                totalSplitQuantity=totalSplitQuantity+iorder.getSplitVolume();
                totalSplitCount=totalSplitCount+iorder.getSplitActivity();
                totalPieces=totalPieces+iorder.getPieces();
            }
            List<ProductProduction> productProductions=productProductionService.querySelective(startDay.toString(),endDay.toString(),"",1,30,"desc","");
            for(ProductProduction production:productProductions){
                if(IorderSpecial.isDateInWeek(production.getProductionDate(),startDay,endDay)){
                    totalProduction=totalProduction+production.getProductActivity();
                }
            }
            dailySummeryTemplate.setProductCount(totalProduction);

            dailySummeryTemplate.setTotalOrderCount(Double.valueOf(decimalFormat.format(totalOrderCount)));
            dailySummeryTemplate.setTotalSplitCount(Double.valueOf(decimalFormat.format(totalSplitCount)));
            dailySummeryTemplate.setIntervalDecay(Double.valueOf(decimalFormat.format(totalSplitCount-totalOrderCount)));
            dailySummeryTemplate.setDate(startDay+"  至  "+endDay);
            dailySummeryTemplate.setTotalPieces(totalPieces);
            dailySummeryTemplate.setProductName("碘131化钠口服溶液");
            dailySummeryTemplates.add(dailySummeryTemplate);
           totalOrderCount=0.00;
           totalSplitQuantity=0.00;
           totalSplitCount=0.00;
            totalPieces=0;
            totalProduction=0.00;
        }

        Map<String,Object> data=new HashMap<>();
        data.put("items",dailySummeryTemplates);
        long total = PageInfo.of(dailySummeryTemplates).getTotal();
        data.put("total",total);

        return ResponseUtil.ok(data);



    }

    @RequiresPermissions("admin:reportForm:byMonth")
    @RequiresPermissionsDesc(menu = { "数据统计", "按月份统计" }, button = "查询")
    @PostMapping("/byMonth")
    public Object listByMonth(@RequestBody ReportFormPageQuery reportFormPageQuery) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘131生产发货管理->查询,请求参数:instrumentNumber:{},instrumentName:{},page:{}", reportFormPageQuery.toString());
        DecimalFormat decimalFormat = new DecimalFormat("#0.00");
        PageHelper.startPage(reportFormPageQuery.getPage(), reportFormPageQuery.getLimit());
        String startTime = "";
        String endTime = "";
        List<String> ste = new ArrayList<>();
        ste = reportFormPageQuery.getStartToEnd();
        if (ste != null && !ste.isEmpty()) {
            startTime = ste.get(0).substring(0, 10);
            endTime = ste.get(1).substring(0, 10);
            logger.info(ste.toString());
            logger.info(startTime + endTime);
        }
        if(startTime=="" && endTime==""){
            endTime=LocalDate.now().toString();
            startTime=LocalDate.now().minus(12, ChronoUnit.MONTHS).toString();
        }
        /*Map<String,String> monthDates=IorderSpecial.getMonthDates(s)*/
        List<WeekRange> weekRanges= IorderSpecial.getMonthDates(LocalDate.parse(startTime),LocalDate.parse(endTime));
        Double totalOrderCount=0.00;
        Double totalSplitQuantity=0.00;
        Double totalSplitCount=0.00;
        Integer totalPieces=0;
        Double totalProduction=0.00;
        List<DailySummeryTemplate> dailySummeryTemplates=new ArrayList<>(); //根据每日分装量汇总
        for(WeekRange weekRange:weekRanges){
            DailySummeryTemplate dailySummeryTemplate=new DailySummeryTemplate();
            LocalDate startDay=weekRange.getStart();
            /* String start=startDay+"T07:47:04.079Z";*/
            LocalDate endDay=weekRange.getEnd();
            /*       String end=endDay+"T07:47:04.079Z";*/
            List<Iorders> iorders=iorderService.querySelective(startDay.toString(),endDay.toString(),"",1,30,"desc","");
            for(Iorders iorder:iorders){
                totalOrderCount=totalOrderCount+iorder.getOrderCount1()+iorder.getOrderCount2()+iorder.getOrderCount3();
                totalSplitQuantity=totalSplitQuantity+iorder.getSplitVolume();
                totalSplitCount=totalSplitCount+iorder.getSplitActivity();
                totalPieces=totalPieces+iorder.getPieces();
            }
            List<ProductProduction> productProductions=productProductionService.querySelective(startDay.toString(),endDay.toString(),"",1,30,"desc","");
            for(ProductProduction production:productProductions){
                if(IorderSpecial.isDateInWeek(production.getProductionDate(),startDay,endDay)){
                    totalProduction=totalProduction+production.getProductActivity();
                }
            }
            dailySummeryTemplate.setProductCount(totalProduction);

            dailySummeryTemplate.setTotalOrderCount(Double.valueOf(decimalFormat.format(totalOrderCount)));
            dailySummeryTemplate.setTotalSplitCount(Double.valueOf(decimalFormat.format(totalSplitCount)));
            dailySummeryTemplate.setIntervalDecay(Double.valueOf(decimalFormat.format(totalSplitCount-totalOrderCount)));
            dailySummeryTemplate.setDate(startDay+"  至  "+endDay);
            dailySummeryTemplate.setTotalPieces(totalPieces);
            dailySummeryTemplate.setProductName("碘131化钠口服溶液");
            dailySummeryTemplates.add(dailySummeryTemplate);
            totalOrderCount=0.00;
            totalSplitQuantity=0.00;
            totalSplitCount=0.00;
            totalPieces=0;
            totalProduction=0.00;
        }

        Map<String,Object> data=new HashMap<>();
        data.put("items",dailySummeryTemplates);
        long total = PageInfo.of(dailySummeryTemplates).getTotal();
        data.put("total",total);

        return ResponseUtil.ok(data);
    }

    @RequiresPermissions("admin:reportForm:byYear")
    @RequiresPermissionsDesc(menu = { "数据统计", "按月份统计" }, button = "查询")
    @PostMapping("/byYear")
    public Object listByYear(@RequestBody ReportFormPageQuery reportFormPageQuery) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘131生产发货管理->查询,请求参数:instrumentNumber:{},instrumentName:{},page:{}", reportFormPageQuery.toString());
        DecimalFormat decimalFormat = new DecimalFormat("#0.00");
        PageHelper.startPage(reportFormPageQuery.getPage(), reportFormPageQuery.getLimit());
        String startTime = "";
        String endTime = "";
        List<String> ste = new ArrayList<>();
        ste = reportFormPageQuery.getStartToEnd();
        if (ste != null && !ste.isEmpty()) {
            startTime = ste.get(0).substring(0, 10);
            endTime = ste.get(1).substring(0, 10);
            logger.info(ste.toString());
            logger.info(startTime + endTime);
        }
        if(startTime=="" && endTime==""){
            endTime=LocalDate.now().toString();
            startTime=LocalDate.now().minus(12, ChronoUnit.MONTHS).toString();
        }
        /*Map<String,String> monthDates=IorderSpecial.getMonthDates(s)*/
        List<WeekRange> weekRanges= IorderSpecial.getYearDates(LocalDate.parse(startTime),LocalDate.parse(endTime));
        Double totalOrderCount=0.00;
        Double totalSplitQuantity=0.00;
        Double totalSplitCount=0.00;
        Integer totalPieces=0;
        Double totalProduction=0.00;
        List<DailySummeryTemplate> dailySummeryTemplates=new ArrayList<>(); //根据每日分装量汇总
        for(WeekRange weekRange:weekRanges){
            DailySummeryTemplate dailySummeryTemplate=new DailySummeryTemplate();
            LocalDate startDay=weekRange.getStart();
            /* String start=startDay+"T07:47:04.079Z";*/
            LocalDate endDay=weekRange.getEnd();
            /*       String end=endDay+"T07:47:04.079Z";*/
            List<Iorders> iorders=iorderService.querySelective(startDay.toString(),endDay.toString(),"",1,30,"desc","");
            for(Iorders iorder:iorders){
                totalOrderCount=totalOrderCount+iorder.getOrderCount1()+iorder.getOrderCount2()+iorder.getOrderCount3();
                totalSplitQuantity=totalSplitQuantity+iorder.getSplitVolume();
                totalSplitCount=totalSplitCount+iorder.getSplitActivity();
                totalPieces=totalPieces+iorder.getPieces();
            }
            List<ProductProduction> productProductions=productProductionService.querySelective(startDay.toString(),endDay.toString(),"",1,30,"desc","");
            for(ProductProduction production:productProductions){
                if(IorderSpecial.isDateInWeek(production.getProductionDate(),startDay,endDay)){
                    totalProduction=totalProduction+production.getProductActivity();
                }
            }
            dailySummeryTemplate.setProductCount(totalProduction);

            dailySummeryTemplate.setTotalOrderCount(Double.valueOf(decimalFormat.format(totalOrderCount)));
            dailySummeryTemplate.setTotalSplitCount(Double.valueOf(decimalFormat.format(totalSplitCount)));
            dailySummeryTemplate.setIntervalDecay(Double.valueOf(decimalFormat.format(totalSplitCount-totalOrderCount)));
            dailySummeryTemplate.setDate(startDay+"  至  "+endDay);
            dailySummeryTemplate.setTotalPieces(totalPieces);
            dailySummeryTemplate.setProductName("碘131化钠口服溶液");
            dailySummeryTemplates.add(dailySummeryTemplate);
            totalOrderCount=0.00;
            totalSplitQuantity=0.00;
            totalSplitCount=0.00;
            totalPieces=0;
            totalProduction=0.00;
        }

        Map<String,Object> data=new HashMap<>();
        data.put("items",dailySummeryTemplates);
        long total = PageInfo.of(dailySummeryTemplates).getTotal();
        data.put("total",total);

        return ResponseUtil.ok(data);

    }

    @RequiresPermissions("admin:reportForm:byDay")
    @RequiresPermissionsDesc(menu = { "数据统计", "按月份统计" }, button = "查询")
    @PostMapping("/byDay")
    public Object listByDays(@RequestBody ReportFormPageQuery reportFormPageQuery) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘131生产发货管理->查询,请求参数:instrumentNumber:{},instrumentName:{},page:{}", reportFormPageQuery.toString());
        DecimalFormat decimalFormat = new DecimalFormat("#0.00");

        String startTime = "";
        String endTime = "";
        List<String> ste = new ArrayList<>();
        ste = reportFormPageQuery.getStartToEnd();
        if (ste != null && !ste.isEmpty()) {
            startTime = ste.get(0).substring(0, 10);
            endTime = ste.get(1).substring(0, 10);
            logger.info(ste.toString());
            logger.info(startTime + endTime);
        }
        List<DailySummeryTemplate> dailySummeryTemplates=new ArrayList<>(); //根据每日分装量汇总
        /* List<MonthSummeryTemplate> monthSummeryTemplates=new ArrayList<>(); //根据产品批号汇总*/
        List<ProductProduction> productProductions=productProductionService.querySelective(startTime,endTime,"",0,0,"production_date","desc");
        //现在开始按起始时间（每日分装量）统计
        List<Iorders> iorders=iorderService.querySelective(startTime,endTime,null,1,20,"date","desc");
        Double orderCount=0.00;
        Double splitQuantity=0.00;
        Double splitCount=0.00;//
        Double totalOrderCount=0.00;
        Double totalSplitQuantity=0.00;
        Double totalSplitCount=0.00;
        List<String> dates=new ArrayList<>();
        for(Iorders iorder:iorders){

            if(!dates.contains(iorder.getDate())){
                dates.add(iorder.getDate());
            }


        }
        for(ProductProduction production2:productProductions) {
            MonthSummeryTemplate monthSummeryTemplate = new MonthSummeryTemplate();
            for (Iorders iorders3 : iorders){
                if (iorders3.getBatchNumber()!=null && iorders3.getBatchNumber().equals(production2.getBatchNumber())){
                    splitQuantity = iorders3.getSplitVolume();
                    orderCount = iorders3.getOrderCount1() + iorders3.getOrderCount2() + iorders3.getOrderCount3();
                    splitCount = iorders3.getSplitActivity();
                    totalOrderCount = totalOrderCount + orderCount;
                    totalSplitQuantity = totalSplitQuantity + splitQuantity;
                    totalSplitCount = totalSplitCount + splitCount;
                }
            }
            totalOrderCount=0.00;
            totalSplitQuantity=0.00;
            totalSplitCount=0.00;
        }

        for(String s:dates){
            DailySummeryTemplate dailySummeryTemplate=new DailySummeryTemplate();
            List<Iorders> iorders2=new ArrayList<>();
            for(Iorders iorders5:iorders){
                if(iorders5.getDate()!=null) {
                    if (iorders5.getDate().equals(s)) {
                        iorders2.add(iorders5);
                    }
                }
            }

            for(Iorders iorder4:iorders2){
                splitQuantity=iorder4.getSplitVolume();
                orderCount=iorder4.getOrderCount1()+iorder4.getOrderCount2()+iorder4.getOrderCount3();
                splitCount=iorder4.getSplitActivity();
                totalOrderCount=totalOrderCount+orderCount;
                totalSplitQuantity=totalSplitQuantity+splitQuantity;
                totalSplitCount=totalSplitCount+splitCount;
            }
            totalOrderCount=Double.valueOf(decimalFormat.format(totalOrderCount));
            totalSplitQuantity=Double.valueOf(decimalFormat.format(totalSplitQuantity));
            totalSplitCount=Double.valueOf(decimalFormat.format(totalSplitCount));
            dailySummeryTemplate.setDate(s);
            dailySummeryTemplate.setProductName("碘131化钠口服溶液");
            dailySummeryTemplate.setTotalSplitCount(totalSplitCount);
            dailySummeryTemplate.setTotalOrderCount(totalOrderCount);
            dailySummeryTemplate.setIntervalDecay(Double.valueOf(decimalFormat.format(totalSplitCount-totalOrderCount)));
            for(ProductProduction production:productProductions){
                if(production.getProductionDate().toString().equals(s)){
                    dailySummeryTemplate.setProductCount(production.getProductActivity());
                }
            }
            dailySummeryTemplates.add(dailySummeryTemplate);
            totalOrderCount=0.00;
            totalSplitQuantity=0.00;
            totalSplitCount=0.00;
        }

        Map<String,Object> data=new HashMap<>();
        /*    data.put("item1",monthSummeryTemplates);*/
        data.put("items",dailySummeryTemplates);

        long total = PageInfo.of(dailySummeryTemplates).getTotal();
        /* long total2 = PageInfo.of(monthSummeryTemplates).getTotal();*/
        data.put("total",total);
        /*        data.put("total2",total2);*/
        PageHelper.startPage(1, 20);

        return ResponseUtil.ok(data);

    }


    @GetMapping("/listByOrder")
    public Object list2(@RequestParam(defaultValue = "2024-01-01") String startTime, @RequestParam(defaultValue = "2024-12-01")String endTime,@RequestParam(value="batchNumber") String batchNumber, @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "20") Integer limit,
                       @RequestParam(defaultValue = "measure_tine") String sort,
                       @RequestParam(defaultValue = "desc") String order) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘131生产发货管理->查询,请求参数:instrumentNumber:{},instrumentName:{},page:{}", page);
          logger.info(sort+order);


        return adminProductProductionService.list(startTime,endTime,batchNumber,page, limit, sort,order);
    }


    /*@RequiresPermissions("admin:productProduction:list")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "查询")
    @GetMapping("/list")
    public Object list22(@RequestParam(defaultValue = "2024-01-01") String startTime, @RequestParam(defaultValue = "2024-12-01")String endTime,@RequestParam(value="batchNumber") String batchNumber, @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "20") Integer limit,@RequestParam(defaultValue = "0") Integer isNew*//*,
                       @Sort @RequestParam(defaultValue = "id") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order*//*) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘131生产发货管理->查询,请求参数:instrumentNumber:{},instrumentName:{},page:{}", page);
        //需要区分数据权限，如果属于品牌商管理员，则需要获取当前用户管理品牌店铺
        *//*   List<Integer> brandIds = null;*//**//*
         *//**//*if (adminDataAuthService.isBrandManager()) {*//**//*
         *//**//*        brandIds = adminDataAuthService.getBrandIds();
            logger.info("运营商管理角色操作，需控制数据权限，brandIds:{}",JSONObject.toJSONString(brandIds));

            if (brandIds == null || brandIds.size() == 0) {
                Map<String, Object> data = new HashMap<>();
                data.put("total", 0L);
                data.put("items", null);

                logger.info("【请求结束】商品管理->商品管理->查询,响应结果:{}", JSONObject.toJSONString(data));
                return ResponseUtil.ok(data);
          *//**//**//**//*  }*//**//*
         *//**//*     }*//*


        return adminProductProductionService.list(startTime,endTime,batchNumber,page, limit,isNew*//*, sort,order*//*);
    }*/




    @GetMapping("/getInfoByOrderCounts")
    public Object getInfoByOrderCount(@RequestParam(value="batchNumber") String batchNumber,@RequestParam(value="orderCount") String orderCount,@RequestParam(value="useTime") String useTime,@RequestParam(value="piece") Integer piece) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘131生产发货管理->查询,请求参数:instrumentNumber:{},instrumentName:{},page:{}", orderCount);
        //需要区分数据权限，如果属于品牌商管理员，则需要获取当前用户管理品牌店铺
        /*   List<Integer> brandIds = null;*//*
         *//*if (adminDataAuthService.isBrandManager()) {*//*
         *//*        brandIds = adminDataAuthService.getBrandIds();
            logger.info("运营商管理角色操作，需控制数据权限，brandIds:{}",JSONObject.toJSONString(brandIds));

            if (brandIds == null || brandIds.size() == 0) {
                Map<String, Object> data = new HashMap<>();
                data.put("total", 0L);
                data.put("items", null);

                logger.info("【请求结束】商品管理->商品管理->查询,响应结果:{}", JSONObject.toJSONString(data));
                return ResponseUtil.ok(data);
          *//**//*  }*//*
         *//*     }*/


        return adminProductProductionService.getOrderInfo(batchNumber,orderCount,useTime,piece/*, sort,order*/);
    }

/*    @GetMapping("/catAndBrand")
    public Object catAndBrand() {
        return adminInstrumentService.catAndBrand();
    }*/

    /**
     * 编辑商品
     *
     * @param productProductionAll
     * @return
     */
    @RequiresPermissions("admin:productProduction:update")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody ProductProductionAll productProductionAll) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘131生产发货管理->生产列表->编辑,请求参数:{}", JSONObject.toJSONString(productProductionAll));

        return adminProductProductionService.update(productProductionAll);
    }

    @RequiresPermissions("admin:productProduction:insertMany")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "导入")
    @GetMapping("/insertMany")
    public boolean addUser(@RequestParam("file") MultipartFile file) {
        boolean a = false;
        String fileName = file.getOriginalFilename();
        try {
            /* a = itestService.batchImport(fileName, file);*/
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  a;
    }

    /**
     * 删除器材
     *
     * @param productProduction
     * @return
     */
 /*   @RequiresPermissions("admin:productProduction:deleteProductProduction")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody ProductProduction productProduction) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘131生产发货管理->删除,请求参数:{}", JSONObject.toJSONString(productProduction));

        return adminProductProductionService.delete(productProduction);
    }
*/
    /*@RequiresPermissions("admin:instrument:insertMany")
    public Object insertMany(@RequestBody List<InstrumentAll> list){

        return
    }
*/
    /**
     * 添加商品
     *哈哈哈哈哈哈哈哈哈

     * @return
     */
    @RequiresPermissions("admin:productProduction:create")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "添加")
    @GetMapping("/create")
    public Object create(@RequestParam(value = "batchNumber")String batchNumber,
                         Integer rawConcentration,
                         String rawNumber1,
                         String rawNumber2,
                         Integer oralConcentration,
                         @RequestParam(value = "sampleRetention")Double sampleRetention,
                         @RequestParam(value = "productionDate")String productionDate,
                         Double productionCapacity,
                         @RequestParam(value = "measureTime")String measureTime,
                         Double productionActivity) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 碘131生产发货管理->订单列表->新增,请求参数:{}", JSONObject.toJSONString(productProductionService));
        DecimalFormat decimalFormat = new DecimalFormat("#0.00");
        ProductProduction productProduction = new ProductProduction();
        productProduction.setBatchNumber(batchNumber);
        if(productionDate!=null){
            String s=productionDate.substring(0,10);
            productProduction.setProductionDate(LocalDate.parse(s));
        }
        if(measureTime!=null){
            productProduction.setMeasureTine(LocalDateTime.parse(measureTime));
        }
        productProduction.setSampleRetention(sampleRetention);


        productProduction.setProductActivity(productionActivity);
        productProduction.setProductCapacity(productionCapacity);
        productProduction.setRemainingActivity(productionActivity-sampleRetention*oralConcentration/1000);
        productProduction.setRemainingCapacity(productionCapacity-sampleRetention);
       productProduction.setOralConcentration(oralConcentration);
       productProduction.setRawNumber1(rawNumber1);
       productProduction.setRawNumber2(rawNumber2);
       productProduction.setRawConcentration(rawConcentration);

        logger.info(productProduction.toString());
        return adminProductProductionService.create(productProduction);
    }

    /**
     * 器材详情
     *
     * @param id
     * @return
     */
    @RequiresPermissions("admin:productProduction:read")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "详情")
    @GetMapping("/detail")
    public Object detail(@NotNull Integer id) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘生产管理->详情,请求参数,id:{}", id);
        logger.info("hehehehheheh");
        return adminProductProductionService.detail(id);
    }


    @RequiresPermissions("admin:productProduction:read")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "查看产品信息")
    @GetMapping("/info")
    public Object detail(@NotNull String batchNumber) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘生产管理->详情,请求参数,id:{}", batchNumber);
        logger.info("根据产品信息查找产品");
        return adminProductProductionService.detail(batchNumber);
    }

    /*@RequiresPermissions("admin:productProduction:read")*/
    /*@RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "查看产品信息")*/
    @PostMapping("/queryBatchNumbers")
    public Object getBatchNumbers(@RequestParam(defaultValue = "2024-01-01") String startTime, @RequestParam(defaultValue = "2024-12-01")String endTime,String batchNumber) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘生产管理->详情,请求参数,id:{}", startTime+endTime);
        logger.info("查找所有产品批号");
        Map<String,Object> data=new HashMap<>();
        Map<String,String> batchNumbers2=new TreeMap<>();
        Map<String,String> batchNumbers3=new TreeMap<>();
        Object batchNumbers=null;
        List<ProductProduction> productProductions=productProductionService.querySelective(startTime,endTime,batchNumber,1,20,"production_date","desc");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for(ProductProduction production:productProductions){
            if(production.getIsEnd()==Boolean.FALSE) {
                String bn = production.getBatchNumber();
                batchNumbers2.put(bn,dateFormat.format(Date.valueOf(bn)));
            }
        }
        batchNumbers2.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())

               /* .forEach(entry ->
                        *//*System.out.println(dateFormat.format(entry.getKey()) + ": " + entry.getValue())*//*
                )*/;
       /* batchNumbers=batchNumbers2.stream()
                .collect(Collectors.groupingBy(s -> s.substring(0, 10)))
                .entrySet()
                .stream()
                .map(entry -> {
                    Map<String, Object> group = Map.of(
                            "label", entry.getKey().substring(0,10),
                            "options", entry.getValue()*//*.stream().map(option -> Map.of("value", option, "label", option)).collect(Collectors.toList())*//*
                    );
                    return group;
                })
                .collect(Collectors.toList());*/
        data.put("batchNumbers",batchNumbers2);
        /*logger.info(batchNumbers.toString());*/
        return ResponseUtil.ok(data);
    }

    @PostMapping("/queryBatchNumbers2")
    public Object getBatchNumbers2(@RequestParam(defaultValue = "2024-01-01") String startTime, @RequestParam(defaultValue = "2024-12-01")String endTime,String batchNumber) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘生产管理->详情,请求参数,id:{}", startTime+endTime);
        logger.info("查找所有产品批号");
        Map<String,Object> data=new HashMap<>();
        Map<String,String> batchNumbers2=new TreeMap<>();
        Map<String,String> batchNumbers3=new TreeMap<>();
        Object batchNumbers=null;
        List<ProductProduction> productProductions=productProductionService.querySelective(startTime,endTime,batchNumber,1,20,"production_date","desc");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for(ProductProduction production:productProductions){

                String bn = production.getBatchNumber();
                batchNumbers2.put(bn,dateFormat.format(Date.valueOf(bn)));

        }
        batchNumbers2.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())

        /* .forEach(entry ->
         *//*System.out.println(dateFormat.format(entry.getKey()) + ": " + entry.getValue())*//*
                )*/;
       /* batchNumbers=batchNumbers2.stream()
                .collect(Collectors.groupingBy(s -> s.substring(0, 10)))
                .entrySet()
                .stream()
                .map(entry -> {
                    Map<String, Object> group = Map.of(
                            "label", entry.getKey().substring(0,10),
                            "options", entry.getValue()*//*.stream().map(option -> Map.of("value", option, "label", option)).collect(Collectors.toList())*//*
                    );
                    return group;
                })
                .collect(Collectors.toList());*/
        data.put("batchNumbers",batchNumbers2);
        /*logger.info(batchNumbers.toString());*/
        return ResponseUtil.ok(data);
    }
    @PostMapping("/setEnd")
    public Object setEnd(@RequestBody List<ProductsTemplate> productsTemplates){

        if(productsTemplates!=null){
            for(ProductsTemplate productsTemplate:productsTemplates){
                String batchNumber=productsTemplate.getBatchNumber();
                Integer id=productsTemplate.getId();
                ProductProduction production=productProductionService.findById(id);
                production.setIsEnd(true);
                productProductionService.updateById(production);
                productsTemplate.setIsEnd("true");
            }
            Map<String,Object> data=new HashMap<>();
            data.put("total",productsTemplates.size());
            return ResponseUtil.ok(data);
        }else{
            return null;
        }


    }


    @RequiresPermissions("admin:productProduction:read")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "详情")
    @GetMapping("/more")
    public Object detail2(@NotNull Integer id) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘生详情,请求参数,id:{}", id);
        logger.info("heheh胜多负少h");
        return adminProductProductionService.detail(id);
    }
    /**
     * 删除生产信息
     *
     * @param productProduction
     * @return
     */
    @RequiresPermissions("admin:productProduction:deleteProductProduction")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "删除")
    @PostMapping("/deleteProductProduction")
    public Object delete(@RequestBody ProductProduction productProduction) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 器材管理->器材管理->删除,请求参数:{}", JSONObject.toJSONString(productProduction));

        return adminProductProductionService.delete(productProduction);
    }

/*    @RequiresPermissions("admin:productProduction:read")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "详情")
    @GetMapping("/more")
    public Object detail2(@NotNull Integer id) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘生详情,请求参数,id:{}", id);
        logger.info("heheh胜多负少h");
        return adminProductProductionService.detail(id);
    }*/


}
